/**
 * Copyright 2016-2018 mobaas.com
 */
package com.mobaas.devops.health;

import java.io.IOException;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.mobaas.devops.HealthChecker;
import com.mobaas.devops.HealthResult;
import com.mobaas.devops.HttpHealthResult;

/**
 * HTTP方式health检查实现
 * @author billy zhang
 *
 */
public class HttpHealthChecker implements HealthChecker {

	@Override
	public <T extends HealthResult> T check(Map<String, Object> data) {
		
		HttpHealthResult result = new HttpHealthResult();
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
		try {
			String url = (String)data.get("url");
			HttpGet httpGet = new HttpGet(url);
	    		
			RequestConfig.Builder builder = RequestConfig.custom();
			if (data.containsKey("connectTimeout"))
			     builder.setConnectTimeout((Integer)data.get("connectTimeout"));
			if (data.containsKey("readTimeout"))
			     builder.setSocketTimeout((Integer)data.get("readTimeout"));
			
			httpGet.setConfig(builder.build());  

	    		CloseableHttpResponse response = httpClient.execute(httpGet);
	    		result.setHttpStatus(response.getStatusLine().getStatusCode());
	    		result.setContent(EntityUtils.toString(response.getEntity()));
	    		
	    		response.close();
		} catch (IOException ex) {
			ex.printStackTrace();
			result.setReqStatus(-1);
	    		result.setReqError(ex.getMessage());
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return (T)result;
	}
}
